package com.kamistoat.netty.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * Scattering: 将数据写入到buffer时，可以采用buffer数组依次写入()
 * Gathering: 在将数据从buffer中读出时，可以采用buffer数组依次读()
 */
public class ScatteringAndGathering {
    public static void main(String[] args) throws Exception {
        // 使用ServerSocketChannel 和 SocketChannel

        // 创建一个 ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 分配一个Socket端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        // 绑定端口到ServerSocketChannel并启动监听
        serverSocketChannel.bind(inetSocketAddress);

        // 在服务器端创建一个长度为2的buffer数组，并为这两个buffer分配空间
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        // 等待客户端链接。暂时只考虑单客户端，还未引入Selector
        SocketChannel socketChannel = serverSocketChannel.accept();

        int messageLength = 8;
        while (true) {
            // 依次向buffer数组写入
            int byteRead = 0;
            while (byteRead < messageLength) {
                long read = socketChannel.read(byteBuffers);
                byteRead += read;
                System.out.println("byteRead:" + byteRead);
                Arrays.stream(byteBuffers).map(byteBuffer -> {
                    return "position:" + byteBuffer.position() + ",limit:" + byteBuffer.limit();
                }).forEach(System.out::println);
            }

            Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.flip());

            // 从buffer数组中依次读取
            long byteWrite = 0;
            while (byteWrite < messageLength) {
                long write = socketChannel.write(byteBuffers);
                byteWrite += write;
                System.out.println("byteWrite:" + byteWrite);
            }

            Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.clear());
            System.out.println("byteRead:" + byteRead + ", byteWrite:" + byteWrite);
        }


    }
}
